from django.shortcuts import render
from django.views import View
from goods.models import SKU
from django import http
from django_redis import get_redis_connection
# Create your views here.
import base64
import pickle
import json

class CartsSelectAllView(View):
    '''全选购物车'''

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis购物车
            reids_conn = get_redis_connection('carts')
        else:

            # 获取cookie中的购物车数据，并且判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')

            # 构造响应对象
            response = http.JsonResponse({'code': '200', 'errmsg': 'OK'})

            if cart_str:
                # 将 cart_str转成bytes类型的字符串
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将cart_dict_bytes转成真正的字典
                cart_dict = pickle.loads(cart_dict_bytes)

                # 遍历所有的购物车记录
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected  # True / False

                # 将cart_dict转成bytes类型的字典
                cart_dict_bytes = pickle.dumps(cart_dict)
                # 将cart_dict_bytes转成bytes类型的字符串
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                # 将cart_str_bytes转成字符串
                cookie_cart_str = cart_str_bytes.decode()

                # 重写将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str)

            return response



class CartsView(View):
    ''''购物车页面'''

    def post(self,request):
        '''保存购物车'''
        #接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        print(type(sku_id))
        print(sku_id)
        selected = json_dict.get('selected',True)
        #校验参数
        if not all([sku_id,count]):
            return  http.HttpResponseForbidden('缺少必传参数')
        # try:
        #     SKU.objects.get(sku_id)
        # except SKU.DoesNotExist:
        #     return http.HttpResponseForbidden('参数sku_id错误')
        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('参数count错误')
        if selected:
            if not isinstance(selected,bool):
                return http.HttpResponseForbidden('参数selecet错误')
        #判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 如果已经登录，操作redis数据
            redis_con = get_redis_connection('carts')
            #需要以增量的形式保存商品数据
            redis_con.hincrby('carts_%s' % user.id, sku_id , count)
            #保存商品勾选状态
            if selected:
                redis_con.sadd('selectes_%s' % user.id,sku_id)
            #响应结果
            return http.JsonResponse({'code':'200','errmas':'ok'})
        else:
            # 如果未登录，操作cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                #将 cart_str_bytes 转为bytes类型的字符串
                cart_str_bytes = cart_str.encode()
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}
            #判断当前要添加的商品再dict中是否存在
            if sku_id not in cart_dict:
                #购物车中存在商品
                # origin_count= cart_dict[sku_id]['count']
                origin_count = count
                count +=origin_count
            cart_dict[sku_id]={
                    'count':count,
                    'selected':selected
            }
            cart_dict_bytes = pickle.dumps(cart_dict)
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            cookie_cart_str = cart_str_bytes.decode()

            #将新的购物车数据写入到cookie
            response = http.JsonResponse({'code':'200','errmsg':'ok'})
            response.set_cookie('carts',cookie_cart_str)
        return response





        #响应结果

    def put(self, request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku =SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_con = get_redis_connection('carts')
            redis_con.hset('carts_%s '%user.id,sku_id,count)
            #修改勾选状态
            if selected:
                redis_con.sadd('sellected_%s'%user.id,sku_id)
            else:
                redis_con.srem('sellected_%s'%user.id,sku_id)
            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return http.JsonResponse({'code': '200', 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        else:
            # 用户未登录，修改cookie购物车
            # 用户未登录，修改cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            # 因为接口设计为幂等的，直接覆盖
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = http.JsonResponse({'code': '200', 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str)
            return response

    def delete(self, request):
        """删除购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:


            redis_conn = get_redis_connection('carts')
            redis_conn.hdel('carts_%s'%user.id,sku_id)
            redis_conn.srem('selected_%s' %user.id,sku_id)
            return http.JsonResponse({'code':'200','errmsg':'ok'})
        else:
            # 用户未登录，删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
                # 创建响应对象
            response = http.JsonResponse({'code': '200', 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
                cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str)
            return response



    def get(self,request):
        '''查询购物车'''
        user = request.user
        if user.is_authenticated:
            redis_con =get_redis_connection('carts')
            redis_cart = redis_con.hgetall('carts_%s' % user.id)
            redis_selected = redis_con.smembers('selected_%s' % user.id)
            #进行数据结构的构造，合并数据，数据结构跟未登录的用户购物车结构一致
            cart_dict = {}
            for sku_id ,count in redis_cart.items():
                cart_dict[int(sku_id)]={
                    'count': int(count),
                    'selected':sku_id in redis_selected
                }
        else:
            # 如果未登录，操作cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将 cart_str_bytes 转为bytes类型的字符串
                cart_str_bytes = cart_str.encode()
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}
        #构造响应数据库结构
        #获取字典中的key的方法
            # 构造购物车渲染数据
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })

        context = {
            'cart_skus': cart_skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)







